﻿using ICodeShare.UI.Controls.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace ICodeShare.UI.Controls.Demo.ExampleViews
{
    /// <summary>
    /// AnimatedPanelView.xaml 的交互逻辑
    /// </summary>
    public partial class AnimatedPanelView : UserControl
    {
       private const int NumberOfRows = 4;
        private const int NumberOfColumns = 4;
        private const double DesiredAspectRatio = 1024.0 / 768.0;

        private readonly Random random = new Random();

        private IDictionary<string, IList<UIElement>> backgrounds = new Dictionary<string, IList<UIElement>>();

        public AnimatedPanelView()
        {
            InitializeComponent();
            this.Loaded += AnimatedPanelView_Loaded;
            backgroundGrid.SizeChanged += GridBackground_SizeChanged;
            backgroundGrid.Animator = new FractionDistanceAnimator(0.1);

            foreach (string name in new[] { "Jellyfish", "Koala", "Penguins" })
            {
                backgrounds[name] = new List<UIElement>();
                BitmapSource[,] tiles = SplitImage(LoadImage(String.Format("..\\Debug\\Images\\{0}.jpg", name)), NumberOfRows, NumberOfColumns);
                for (int row = 0; row < NumberOfRows; ++row)
                {
                    for (int column = 0; column < NumberOfColumns; ++column)
                    {
                        Image image = new Image();
                        image.Source = tiles[row, column];
                        image.SetValue(Grid.RowProperty, row);
                        image.SetValue(Grid.ColumnProperty, column);
                        backgroundGrid.Children.Add(image);
                        backgrounds[name].Add(image);
                    }
                }
            }

            RecalculateOffscreenPoints();

            SizeChanged += (s, e) => RecalculateOffscreenPoints();
        }

        void AnimatedPanelView_Loaded(object sender, RoutedEventArgs e)
        {
            this.Loaded -= AnimatedPanelView_Loaded;
            string theJabberwock = "''Beware the Jabberwock, my son! The jaws that bite, the claws that catch! Beware the Jubjub bird, and shun The frumious Bandersnatch!'' He took his vorpal sword in hand: Long time the manxome foe he sought -- So rested he by the Tumtum tree, And stood awhile in thought. And, as in uffish thought he stood, The Jabberwock, with eyes of flame, Came whiffling through the tulgey wood, And burbled as it came! One, two! One, two! And through and through The vorpal blade went snicker-snack! He left it dead, and with its head He went galumphing back.''And, has thou slain the Jabberwock? Come to my arms, my beamish boy! O frabjous day! Callooh! Callay!' He chortled in his joy.";
            foreach (string word in theJabberwock.Split(' '))
            {
                textPanel.Children.Add(new Label { Content = word });
            }
        }

        private void Vertical_Click(object sender, RoutedEventArgs e)
        {
            theStack.Orientation = Orientation.Vertical;
        }

        private void Horizontal_Click(object sender, RoutedEventArgs e)
        {
            theStack.Orientation = Orientation.Horizontal;
        }

        private void RecalculateOffscreenPoints()
        {
            foreach (UIElement element in backgroundGrid.Children)
            {
                element.SetValue(AnimationBase.OverridePositionProperty, GenerateOffscreenPoint());
            }
        }

        private Point GenerateOffscreenPoint()
        {
            double radius = Math.Max(backgroundGrid.ActualWidth, backgroundGrid.ActualHeight) + Math.Max(backgroundGrid.ActualWidth / (double)NumberOfColumns, backgroundGrid.ActualHeight / (double)NumberOfRows);
            return new Point
                (
                (backgroundGrid.ActualWidth / 2.0) + Math.Cos(random.NextDouble() * 2.0 * Math.PI) * radius,
                (backgroundGrid.ActualHeight / 2.0) + Math.Sin(random.NextDouble() * 2.0 * Math.PI) * radius
                );

        }

        void GridBackground_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            double ratio = e.NewSize.Width / e.NewSize.Height;
            if (ratio != DesiredAspectRatio)
            {
                backgroundGrid.Height = e.NewSize.Width / DesiredAspectRatio;
            }

        }

        private static BitmapSource LoadImage(string filename)
        {
            BitmapImage image = new BitmapImage();
            image.BeginInit();
            image.UriSource = new Uri(filename, UriKind.RelativeOrAbsolute);
            image.EndInit();

            return image;
        }

        private static BitmapSource[,] SplitImage(BitmapSource source, int rows, int columns)
        {
            BitmapSource[,] result = new BitmapSource[rows, columns];

            int width = (int)(source.Width / columns);
            int height = (int)(source.Height / rows);

            for (int row = 0; row < rows; ++row)
            {
                for(int column = 0; column < columns; ++column)
                {
                    result[row, column] = new CroppedBitmap(source, new Int32Rect(column * width, row * height, width, height));  
                }
            }

            return result;
        }

        private void ToggleBackground(string name)
        {
            foreach (UIElement element in backgroundGrid.Children)
            {
                element.SetValue(AnimationBase.OverrideArrangeProperty, true);
            }

            foreach (UIElement element in backgrounds[name])
            {
                element.SetValue(AnimationBase.OverrideArrangeProperty, false);
            }
        }

        private void Jellyfish_Click(object sender, RoutedEventArgs e)
        {

            ToggleBackground("Jellyfish");
        }

        private void Koala_Click(object sender, RoutedEventArgs e)
        {
            ToggleBackground("Koala");
        }
        
        private void Penguins_Click(object sender, RoutedEventArgs e)
        {
            ToggleBackground("Penguins");
        }
    }
}
